package calao.storage.bdb;

import com.sleepycat.bind.tuple.TupleInput;
import com.sleepycat.bind.tuple.TupleOutput;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.Database;
import com.sleepycat.je.OperationStatus;
import com.sleepycat.je.LockMode;
import com.sleepycat.je.DatabaseException;

class Util {

	static DatabaseEntry toEntry(TupleOutput out) {
		return new DatabaseEntry(out.getBufferBytes(), out.getBufferOffset(),
				out.getBufferLength());
	}

	static TupleInput toInput(DatabaseEntry entry) {
		return new TupleInput(entry.getData(), entry.getOffset(), entry.getSize());
	}

	static void writeInt(int value, byte[] buffer, int offset) 
	{
		buffer[offset++] = (byte)(value>>24);
		buffer[offset++] = (byte)((value>>16)&0xFF);
		buffer[offset++] = (byte)((value>>8)&0xFF);
		buffer[offset++] = (byte)((value)&0xFF);
	}

	static int readInt(byte[] buffer, int offset) 
	{
		return ((buffer[offset++]&0xFF)<<24)
		| ((buffer[offset++]&0xFF)<<16)
		| ((buffer[offset++]&0xFF)<<8)
		| ((buffer[offset]&0xFF));
	}

	static DatabaseEntry toEntry(String string) 
	{
		TupleOutput out = new TupleOutput();
		out.writeString(string);
		return toEntry(out);
	}

	static String toString(DatabaseEntry entry) 
	{
		TupleInput in = toInput(entry);
		return in.readString();
	}

	static String toString(DatabaseEntry entry, int offset) 
	{
		TupleInput in = toInput(entry);
		in.skipFast(offset);
		return in.readString();
	}

	static DatabaseEntry toEntry(int value) 
	{
		TupleOutput out = new TupleOutput();
		out.writeInt(value);
		return toEntry(out);
	}

	static int toInt(DatabaseEntry entry) 
	{
		TupleInput in = toInput(entry);
		return in.readInt();
	}
	
	static DatabaseEntry copy(DatabaseEntry entry)
	{
		return new DatabaseEntry(entry.getData(), entry.getOffset(), entry.getSize());
	}
	
	static DatabaseEntry get(Database db, DatabaseEntry key)
	throws DatabaseException
	{
		DatabaseEntry data = new DatabaseEntry();
		OperationStatus status = db.get(null, key, data, LockMode.DEFAULT);
		return status==OperationStatus.SUCCESS? data : null;
	}

	static DatabaseEntry toEntry(byte value1, String value2) 
	{
		TupleOutput out = new TupleOutput();
		out.writeByte(value1);
		if (value2!=null) out.writeString(value2);
		return toEntry(out);
	}
	
	static boolean arrayContains(Object[] array, Object value)
	{
		for (Object arrayValue : array) {
			if (arrayValue==value) return true;
		}
		return false;
	}

}
